# -*- coding:utf-8 -*-
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from sshtunnel import SSHTunnelForwarder
import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])
import pandas as pd
# Import the backtrader platform
import backtrader as bt
import pymysql
import datetime


# Create a Stratey
class TestStrategy(bt.Strategy):

    params=(
        ('maperiod',20),
           )
    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        #指定价格序列
        self.dataclose=self.datas[0].close
        # 初始化交易指令、买卖价格和手续费
        self.order = None
        self.buyprice = None
        self.buycomm = None

        #添加移动均线指标，内置了talib模块
        self.sma = bt.indicators.SimpleMovingAverage(
                      self.datas[0], period=self.params.maperiod)

    def next(self):
        if self.order: # 检查是否有指令等待执行, 
            return
        # 检查是否持仓   
        if not self.position: # 没有持仓
            #执行买入条件判断：收盘价格上涨突破20日均线
            if self.dataclose[0] > self.sma[0]:
                #执行买入
                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                self.order = self.buy(size=500)         
        else:
            #执行卖出条件判断：收盘价格跌破20日均线
            if self.dataclose[0] < self.sma[0]:
                #执行卖出
                self.log('Sell CREATE, %.2f' % self.dataclose[0])
                self.order = self.sell(size=500)

def getData(startdate,stock):
    with SSHTunnelForwarder(
            ssh_address_or_host=('quant.stock.red', 8922), 
            ssh_password='!Quant@#',
            ssh_username='quant',
            remote_bind_address=('localhost', 3306)) as server:
            try:
                server.start()
                connect_stat = pymysql.Connect(host='127.0.0.1', port=server.local_bind_port, user='root', passwd='!QuantQuant@', db='quant', charset='utf8')
               # print(connect_stat)
                sql_cmd = "select * from stock_bar_day where trade_date > " + startdate + " and ts_code= '" + stock + "'"
                data = pd.read_sql(sql=sql_cmd,con = connect_stat)
                data['trade_date'] = pd.to_datetime(data['trade_date'],format='%Y%m%d')
               # print(data)
                return data
            except(Exception) as e:
                print('e:', e)
            finally:
                connect_stat.close()


if __name__ == '__main__':
    # Create a cerebro entity
    cerebro = bt.Cerebro()

    # Add a strategy
    cerebro.addstrategy(TestStrategy)

    # Datas are in a subfolder of the samples. Need to find where the script is
    # because it could have been called from anywhere
  #  today = datetime.date.today().__str__().replace("-", "")
    df = getData('20190101','002475.SZ').set_index('trade_date')
   # print(df)
    # Create a Data Feed

    data = bt.feeds.PandasData(dataname=df)

    # Add the Data Feed to Cerebro
    cerebro.adddata(data)

    # Set our desired cash start
    cerebro.broker.setcash(100000.0)

    # Print out the starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    # Run over everything
    cerebro.run()

    # Print out the final result
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
